package hservice

import (
	// "fmt"
	"sync"
	"time"

	"advertoper/db"
	"advertoper/errorcode"

	"doubimeizhi.com/datatable"
	"doubimeizhi.com/utility"

	log "github.com/cihub/seelog"
)

var (
	defaultZJSingleViewInfoService *ZJSingleViewInfoService
)

type ZJSingleViewInfoService struct {
	ZJSingleViewInfo  map[int]*ZJSingleViewItem
	ZJSingleViewLock  *sync.RWMutex
	ZJSingleViewMaxId int
}

func newZJSingleViewInfoService() *ZJSingleViewInfoService {
	service := &ZJSingleViewInfoService{}
	service.ZJSingleViewInfo = make(map[int]*ZJSingleViewItem)
	service.ZJSingleViewLock = new(sync.RWMutex)
	service.ZJSingleViewMaxId = 0
	service.loadDataInit()
	return service
}

func GetZJSingleViewInfoService() *ZJSingleViewInfoService {
	if defaultZJSingleViewInfoService == nil {
		defaultZJSingleViewInfoService = newZJSingleViewInfoService()
	}
	return defaultZJSingleViewInfoService
}

//添加
type ZJSingleViewAddReq struct {
	PublicAdd
	UserZJSingleViewItem
}

//修改
type ZJSingleViewUpdateReq struct {
	PublicUpdate
	ZJSingleViewAddReq
}

//缓存
type ZJSingleViewItem struct {
	PublicItme
	ZJSingleViewUpdateReq
}

//web查询
type ZJSingleViewList struct {
	PublicList
	UserZJSingleViewItem
}

//客户端查询(加上id)
type ZJSingleViewUserList struct {
	Id int `json:"id"`
	UserZJSingleViewItem
}

//load数据
func (p *ZJSingleViewInfoService) loadDataInit() {
	daq := datatable.NewDataTableQuery()
	daq.SetTableName("zjsingleview")
	daq.PushField(&datatable.FiledItem{Alias: "id", Field: "id"})
	daq.PushField(&datatable.FiledItem{Alias: "region_code", Field: "region_code"})
	daq.PushField(&datatable.FiledItem{Alias: "clickable", Field: "clickable"})
	daq.PushField(&datatable.FiledItem{Alias: "title", Field: "title"})
	daq.PushField(&datatable.FiledItem{Alias: "pic_url", Field: "pic_url"})
	daq.PushField(&datatable.FiledItem{Alias: "accessory_pic", Field: "accessory_pic"})
	daq.PushField(&datatable.FiledItem{Alias: "sub_title", Field: "sub_title"})
	daq.PushField(&datatable.FiledItem{Alias: "routers", Field: "routers"})
	daq.PushField(&datatable.FiledItem{Alias: "background_picture", Field: "background_picture"})
	daq.PushField(&datatable.FiledItem{Alias: "background_color", Field: "background_color"})
	daq.PushField(&datatable.FiledItem{Alias: "starttick", Field: "starttick"})
	daq.PushField(&datatable.FiledItem{Alias: "endtick", Field: "endtick"})
	daq.PushField(&datatable.FiledItem{Alias: "insert_tick", Field: "insert_tick", OrderBy: datatable.DESC})
	daq.PushField(&datatable.FiledItem{Alias: "update_tick", Field: "update_tick"})
	daq.PushField(&datatable.FiledItem{Alias: "status", Field: "status"})
	sql, values := daq.GenerateSQL()
	mysqlHelper := db.GetHomePageInfoMysqlHelper()
	results, err := mysqlHelper.Query(sql, values...)
	if err != nil {
		log.Errorf("load zjsingleview list fail ,~~~loadDataInit,err is %s", err.Error())
		return
	}
	p.ZJSingleViewLock.Lock()
	defer p.ZJSingleViewLock.Unlock()
	for _, dt := range results {
		item := &ZJSingleViewItem{}
		item.Id = mysqlHelper.GetColInt(dt, "id")
		item.RegionCode = mysqlHelper.GetColString(dt, "region_code")
		item.ClickAble = mysqlHelper.GetColInt(dt, "clickable")
		item.PicUrl = mysqlHelper.GetColString(dt, "pic_url")
		item.AccessoryPic = mysqlHelper.GetColString(dt, "accessory_pic")
		item.Title = mysqlHelper.GetColString(dt, "title")
		item.SubTitle = mysqlHelper.GetColString(dt, "sub_title")
		item.Routers = mysqlHelper.GetColString(dt, "routers")
		item.BackgroundPicture = mysqlHelper.GetColString(dt, "background_picture")
		item.BackgroundColor = mysqlHelper.GetColString(dt, "background_color")
		item.StartTick = mysqlHelper.GetColInt64(dt, "starttick")
		item.EndTick = mysqlHelper.GetColInt64(dt, "endtick")
		item.InsertTick = mysqlHelper.GetColInt64(dt, "insert_tick")
		item.UpdateTick = mysqlHelper.GetColInt64(dt, "update_tick")
		item.Status = mysqlHelper.GetColInt(dt, "status")

		if item.Id > p.ZJSingleViewMaxId {
			p.ZJSingleViewMaxId = item.Id
		}
		//加入缓存
		p.ZJSingleViewInfo[item.Id] = item
	}
	log.Infof("load zjsingleview data,len is :%d", len(p.ZJSingleViewInfo))
}

//添加
func (p *ZJSingleViewInfoService) ZJSingleViewAdd(req *ZJSingleViewAddReq) (uint, string) {
	if req.EndTick < req.StartTick {
		return 1002, "失效时间不能小于开始有效时间"
	}

	p.ZJSingleViewLock.Lock()
	defer p.ZJSingleViewLock.Unlock()
	//保存
	nowTime := time.Now().Unix()
	p.ZJSingleViewMaxId += 1

	data := make(map[string]*utility.MySQLFieldValue)
	data["id"] = utility.NewMySQLFieldValue(p.ZJSingleViewMaxId, false)
	data["region_code"] = utility.NewMySQLFieldValue(req.RegionCode, false)
	data["clickable"] = utility.NewMySQLFieldValue(req.ClickAble, false)
	data["pic_url"] = utility.NewMySQLFieldValue(req.PicUrl, false)
	data["accessory_pic"] = utility.NewMySQLFieldValue(req.AccessoryPic, false)
	data["title"] = utility.NewMySQLFieldValue(req.Title, false)
	data["sub_title"] = utility.NewMySQLFieldValue(req.SubTitle, false)
	data["background_picture"] = utility.NewMySQLFieldValue(req.BackgroundPicture, false)
	data["background_color"] = utility.NewMySQLFieldValue(req.BackgroundColor, false)
	data["routers"] = utility.NewMySQLFieldValue(req.Routers, false)
	data["starttick"] = utility.NewMySQLFieldValue(req.StartTick, false)
	data["endtick"] = utility.NewMySQLFieldValue(req.EndTick, false)
	data["insert_tick"] = utility.NewMySQLFieldValue(nowTime, false)
	data["update_tick"] = utility.NewMySQLFieldValue(nowTime, false)
	mysqlHelper := db.GetHomePageInfoMysqlHelper()
	_, err := mysqlHelper.SaveRecord(data, "zjsingleview")
	if err != nil {
		log.Errorf("insert zjsingleview fail ,~~~ZJSingleViewAdd,err is %s", err.Error())
		return errorcode.EC_GL_INTERNAL_ERROR, errorcode.Msg(errorcode.EC_GL_INTERNAL_ERROR)
	}
	//添加缓存
	item := &ZJSingleViewItem{}
	item.Id = p.ZJSingleViewMaxId
	item.RegionCode = req.RegionCode
	item.ClickAble = req.ClickAble
	item.PicUrl = req.PicUrl
	item.AccessoryPic = req.AccessoryPic
	item.Title = req.Title
	item.SubTitle = req.SubTitle
	item.BackgroundPicture = req.BackgroundPicture
	item.BackgroundColor = req.BackgroundColor
	item.Routers = req.Routers
	item.StartTick = req.StartTick
	item.EndTick = req.EndTick
	item.InsertTick = nowTime
	item.UpdateTick = nowTime
	item.Status = 1

	p.ZJSingleViewInfo[p.ZJSingleViewMaxId] = item

	return errorcode.EC_GL_SUCCESS, errorcode.Msg(errorcode.EC_GL_SUCCESS)

}

//修改
func (p *ZJSingleViewInfoService) ZJSingleViewUpdate(req *ZJSingleViewUpdateReq) (uint, string) {
	//获取缓存数据
	oldData, ok := p.ZJSingleViewInfo[req.Id]
	if !ok {
		return 101, "row is not invalid"
	}
	currDate := &ZJSingleViewItem{}
	//将老的数据copy一份
	currDate.Id = oldData.Id
	currDate.EndTick = oldData.EndTick
	currDate.InsertTick = oldData.InsertTick
	currDate.BackgroundPicture = oldData.BackgroundPicture
	currDate.BackgroundColor = oldData.BackgroundColor
	currDate.RegionCode = oldData.RegionCode
	currDate.Routers = oldData.Routers
	currDate.StartTick = oldData.StartTick
	currDate.Status = oldData.Status
	currDate.PicUrl = oldData.PicUrl
	currDate.AccessoryPic = oldData.AccessoryPic
	currDate.Title = oldData.Title
	currDate.SubTitle = oldData.SubTitle
	currDate.UpdateTick = oldData.UpdateTick
	currDate.ClickAble = oldData.ClickAble

	updaq := datatable.NewDataTableUpdate()
	updaq.SetTableName("zjsingleview")

	if req.RegionCode != "" {
		updaq.SetUpdateValue("region_code=?", req.RegionCode)
		currDate.RegionCode = req.RegionCode
	}
	if req.ClickAble != 0 {
		updaq.SetUpdateValue("clickable=?", req.ClickAble)
		currDate.ClickAble = req.ClickAble
	}
	if req.PicUrl != "" {
		updaq.SetUpdateValue("pic_url=?", req.PicUrl)
		currDate.PicUrl = req.PicUrl
	}
	if req.AccessoryPic != "" {
		updaq.SetUpdateValue("accessory_pic=?", req.AccessoryPic)
		currDate.AccessoryPic = req.AccessoryPic
	}
	if req.Title != "" {
		updaq.SetUpdateValue("title=?", req.Title)
		currDate.Title = req.Title
	}
	if req.SubTitle != "" {
		if req.SubTitle == "null" {
			req.SubTitle = ""
		}
		updaq.SetUpdateValue("sub_title=?", req.SubTitle)
		currDate.SubTitle = req.SubTitle
	}
	if req.BackgroundPicture != "" {
		if req.BackgroundPicture == "null" {
			req.BackgroundPicture = ""
		}
		updaq.SetUpdateValue("background_picture=?", req.BackgroundPicture)
		currDate.BackgroundPicture = req.BackgroundPicture
	}
	if req.BackgroundColor != "" {
		if req.BackgroundColor == "null" {
			req.BackgroundColor = ""
		}
		updaq.SetUpdateValue("background_color=?", req.BackgroundColor)
		currDate.BackgroundColor = req.BackgroundColor
	}
	if req.Routers != "" {
		updaq.SetUpdateValue("routers=?", req.Routers)
		currDate.Routers = req.Routers
	}
	if req.StartTick != 0 {
		updaq.SetUpdateValue("starttick=?", req.StartTick)
		currDate.StartTick = req.StartTick
	}
	if req.EndTick != 0 {
		updaq.SetUpdateValue("endtick=?", req.EndTick)
		currDate.EndTick = req.EndTick
	}
	if req.Status != 0 {
		if req.Status != 1 && req.Status != -1 {
			req.Status = 1
		}
		updaq.SetUpdateValue("status=?", req.Status)
		currDate.Status = req.Status
	}

	nowTime := time.Now().Unix()
	updaq.SetUpdateValue("update_tick=?", nowTime)
	currDate.UpdateTick = nowTime

	updaq.PushCondition("id=?", req.Id)

	sql, values := updaq.GenerateSQL()
	mysqlHelper := db.GetHomePageInfoMysqlHelper()
	_, err := mysqlHelper.Exec(sql, values...)
	if err != nil {
		log.Errorf("update zjsingleview fail ,~~~ZJSingleViewUpdate,err is %s", err.Error())
		return errorcode.EC_GL_INTERNAL_ERROR, errorcode.Msg(errorcode.EC_GL_INTERNAL_ERROR)
	}
	//更新缓存
	p.ZJSingleViewInfo[req.Id] = currDate

	return errorcode.EC_GL_SUCCESS, errorcode.Msg(errorcode.EC_GL_SUCCESS)
}

//web查询list
func (p *ZJSingleViewInfoService) ZJSingleViewInfoList(status int) []*ZJSingleViewList {
	if status != 1 && status != -1 {
		status = 1
	}
	data := make([]*ZJSingleViewList, 0)
	//遍历缓存取数据
	for _, value := range p.ZJSingleViewInfo {
		item := &ZJSingleViewList{}
		if value.Status == status {
			item.Id = value.Id
			item.ClickAble = value.ClickAble
			item.BackgroundPicture = value.BackgroundPicture
			item.BackgroundColor = value.BackgroundColor
			item.RegionCode = value.RegionCode
			item.Routers = value.Routers
			item.Status = value.Status
			item.PicUrl = value.PicUrl
			item.AccessoryPic = value.AccessoryPic
			item.Title = value.Title
			item.SubTitle = value.SubTitle
			item.InsertTime = time.Unix(value.InsertTick, 0).Format("2006-01-02 15:04:05")
			item.UpdateTime = time.Unix(value.UpdateTick, 0).Format("2006-01-02 15:04:05")
			item.StartTick = time.Unix(value.StartTick, 0).Format("2006-01-02 15:04:05")
			item.EndTick = time.Unix(value.EndTick, 0).Format("2006-01-02 15:04:05")

			data = append(data, item)
		}
	}
	return data
}

//客户端查询数据
func (p *ZJSingleViewInfoService) UserGetZJSingleView(ids []int, regionCode string) []*ZJSingleViewUserList {
	data := make([]*ZJSingleViewUserList, 0)
	//遍历找到满足id的数据
	nowtick := time.Now().Unix()
	for _, dt := range ids {
		for key, value := range p.ZJSingleViewInfo {
			if key == dt {
				//当id满足，再过滤掉不在有效期的数据
				if value.StartTick <= nowtick && value.EndTick >= nowtick && value.Status == 1 &&
					IsRegionCode(value.RegionCode, regionCode) {
					item := &ZJSingleViewUserList{}
					item.Id = value.Id
					item.ClickAble = value.ClickAble
					item.BackgroundPicture = value.BackgroundPicture
					item.BackgroundColor = value.BackgroundColor
					item.Routers = value.Routers
					item.PicUrl = value.PicUrl
					item.AccessoryPic = value.AccessoryPic
					item.Title = value.Title
					item.SubTitle = value.SubTitle

					data = append(data, item)
				}
			}
		}
	}
	return data

}
